<template>
  <div class="article-management">
    <div class="page-header">
      <h2>文章管理</h2>
      <div class="page-info">
        <el-tag size="small" type="info">数据统计</el-tag>
        <span class="stat-item"><i class="el-icon-document"></i> 文章总数：{{ stats.total || 0 }}</span>
        <span class="stat-item"><i class="el-icon-view"></i> 总浏览量：{{ stats.totalViewCount || 0 }}</span>
        <span class="stat-item"><i class="el-icon-view"></i> 今日浏览：<span v-if="statsLoading"><i class="el-icon-loading"></i></span><span v-else>{{ stats.todayViewCount || 0 }}</span></span>
      </div>
    </div>
    
    <!-- 操作工具栏 -->
    <el-card class="box-card" shadow="hover">
      <div class="toolbar">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增文章</el-button>
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item>
            <el-select v-model="searchForm.categoryId" clearable placeholder="文章分类" size="small">
              <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="searchForm.status" clearable placeholder="文章状态" size="small">
              <el-option :value="0" label="草稿"></el-option>
              <el-option :value="1" label="已发布"></el-option>
              <el-option :value="2" label="已下架"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              size="small"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" icon="el-icon-search" @click="onSearch">查询</el-button>
            <el-button size="small" icon="el-icon-refresh" @click="resetSearchForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    
      <!-- 文章表格 -->
      <el-table 
        :data="articleList" 
        border 
        style="width: 100%; margin-top: 15px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); border-radius: 4px;" 
        v-loading="loading"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        :row-class-name="tableRowClassName"
        :stripe="true"
        :highlight-current-row="true">
        <el-table-column prop="id" label="ID" width="60" align="center"></el-table-column>
        <el-table-column label="封面" width="80" align="center">
          <template slot-scope="scope">
            <el-image 
              v-if="scope.row.coverImageUrl" 
              :src="scope.row.coverImageUrl" 
              style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px;"
              :preview-src-list="[scope.row.coverImageUrl]">
            </el-image>
            <span v-else><i class="el-icon-picture-outline" style="color: #ccc;"></i></span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="240" show-overflow-tooltip>
          <template slot-scope="scope">
            <div class="title-cell">
              {{ scope.row.title }}
              <span class="view-count"><i class="el-icon-view"></i> {{ scope.row.viewCount }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="分类" width="120" align="center">
          <template slot-scope="scope">
            <el-tag size="mini" type="info" effect="plain">{{ scope.row.categoryName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusTagType(scope.row.status)" size="small">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" width="180" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.publishTime || scope.row.createTime || scope.row.gmtCreate || scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="220" align="center">
          <template slot-scope="scope">
            <el-button @click="handleEdit(scope.row)" type="text" size="small">
              <i class="el-icon-edit"></i> 编辑
            </el-button>
            <el-button @click="handleView(scope.row)" type="text" size="small">
              <i class="el-icon-view"></i> 查看
            </el-button>
            <el-button 
              v-if="scope.row.status === 0" 
              @click="handlePublish(scope.row)" 
              type="text" 
              size="small">
              <i class="el-icon-upload2"></i> 发布
            </el-button>
            <el-button 
              v-if="scope.row.status === 1" 
              @click="handleUnpublish(scope.row)" 
              type="text" 
              size="small">
              <i class="el-icon-download"></i> 下架
            </el-button>
            <el-button @click="handleDelete(scope.row)" type="text" size="small" style="color: #F56C6C">
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.current"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>

      <!-- 空列表提示 -->
      <div v-if="!loading && (!articleList || articleList.length === 0)" class="empty-container">
        <el-empty description="暂无文章数据">
          <el-button type="primary" size="small" @click="handleAdd">添加文章</el-button>
        </el-empty>
      </div>

      <!-- 数据统计摘要 -->
      <div class="data-summary" v-if="!loading && articleList && articleList.length > 0">
        <div class="summary-item">
          <p class="summary-title">文章总计</p>
          <p class="summary-value">{{ pagination.total }}</p>
        </div>
        <div class="summary-item">
          <p class="summary-title">已发布</p>
          <p class="summary-value">{{ getStatusCount(1) }}</p>
        </div>
        <div class="summary-item">
          <p class="summary-title">草稿</p>
          <p class="summary-value">{{ getStatusCount(0) }}</p>
        </div>
      </div>
    </el-card>

    <!-- 查看文章对话框 -->
    <el-dialog title="文章详情" :visible.sync="viewDialogVisible" width="70%" :before-close="() => viewDialogVisible = false">
      <div v-if="currentArticle" class="article-detail">
        <h1 class="article-title">{{ currentArticle.title }}</h1>
        <div class="article-meta">
          <el-tag size="small">{{ currentArticle.categoryName }}</el-tag>
          <span><i class="el-icon-view"></i> {{ currentArticle.viewCount }}</span>
          <span><i class="el-icon-time"></i> {{ formatDate(currentArticle.publishTime) }}</span>
        </div>
        <div v-if="currentArticle.coverImageUrl" class="article-cover">
          <el-image 
            :src="currentArticle.coverImageUrl" 
            style="max-width: 100%; max-height: 300px;"
            :preview-src-list="[currentArticle.coverImageUrl]">
          </el-image>
        </div>
        <div class="article-content" v-html="currentArticle.content"></div>
        <div v-if="currentArticle.images && currentArticle.images.length" class="article-images">
          <h3>附件图片</h3>
          <div class="image-list">
            <el-image 
              v-for="(img, index) in currentArticle.images" 
              :key="index"
              :src="img.imageUrl" 
              style="width: 120px; height: 120px; margin: 5px; object-fit: cover;"
              :preview-src-list="currentArticle.images.map(i => i.imageUrl)">
            </el-image>
          </div>
        </div>
      </div>
      <div class="dialog-bottom-tips">
        <i class="el-icon-info"></i> 您正在查看文章详情，关闭后可返回文章列表
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="viewDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleEdit(currentArticle)">编辑</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'ArticleManagement',
  data() {
    return {
      loading: false,
      articleList: [],
      categoryOptions: [],
      searchForm: {
        categoryId: null,
        status: null,
        dateRange: null
      },
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      viewDialogVisible: false,
      currentArticle: null,
      stats: {
        total: 0,
        totalViewCount: 0,
        todayViewCount: 0
      },
      statsLoading: false
    };
  },
  created() {
    this.fetchCategoryOptions();
    this.fetchArticleList();
    this.fetchStats();
  },
  methods: {
    // 获取文章列表
    fetchArticleList() {
      this.loading = true;
      axios.get('/api/admin/article/page', {
        params: {
          current: this.pagination.current,
          size: this.pagination.size,
          categoryId: this.searchForm.categoryId,
          status: this.searchForm.status
          // 暂不支持日期范围筛选，后端若支持可添加
          // startDate: this.searchForm.dateRange ? this.formatDateParam(this.searchForm.dateRange[0]) : null,
          // endDate: this.searchForm.dateRange ? this.formatDateParam(this.searchForm.dateRange[1]) : null
        }
      }).then(response => {
        if (response.data.code === 200) {
          const data = response.data.data;
          this.articleList = data.records;
          this.pagination.total = data.total;
        } else {
          this.$message.error(response.data.msg || '获取文章列表失败');
        }
      }).catch(error => {
        console.error('获取文章列表错误', error);
        this.$message.error('获取文章列表失败');
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 获取分类选项
    fetchCategoryOptions() {
      axios.get('/api/admin/article/category', {
        params: { enabled: true }
      }).then(response => {
        if (response.data.code === 200) {
          this.categoryOptions = response.data.data;
        } else {
          this.$message.error(response.data.msg || '获取分类数据失败');
        }
      }).catch(error => {
        console.error('获取分类数据错误', error);
        this.$message.error('获取分类数据失败');
      });
    },
    
    // 搜索文章
    onSearch() {
      this.pagination.current = 1;
      this.fetchArticleList();
    },
    
    // 重置搜索表单
    resetSearchForm() {
      this.searchForm = {
        categoryId: null,
        status: null,
        dateRange: null
      };
      this.onSearch();
    },

    // 计算状态数量
    getStatusCount(status) {
      if (!this.articleList) return 0;
      return this.articleList.filter(item => item.status === status).length;
    },
    
    // 表格行样式
    // eslint-disable-next-line no-unused-vars
    tableRowClassName({row, rowIndex}) {
      if (row.status === 1) {
        return 'published-row';
      } else if (row.status === 2) {
        return 'unpublished-row';
      }
      return '';
    },
    
    // 新增文章
    handleAdd() {
      this.$router.push('/dashboard/article-edit');
    },
    
    // 编辑文章
    handleEdit(row) {
      this.$router.push(`/dashboard/article-edit/${row.id}`);
    },
    
    // 查看文章
    handleView(row) {
      axios.get(`/api/admin/article/${row.id}`)
        .then(response => {
          if (response.data.code === 200) {
            this.currentArticle = response.data.data;
            this.viewDialogVisible = true;
          } else {
            this.$message.error(response.data.msg || '获取文章详情失败');
          }
        })
        .catch(error => {
          console.error('获取文章详情错误', error);
          this.$message.error('获取文章详情失败');
        });
    },
    
    // 发布文章
    handlePublish(row) {
      this.$confirm('确定要发布该文章吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.put(`/api/admin/article/${row.id}/publish`)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('文章发布成功');
              this.fetchArticleList();
            } else {
              this.$message.error(response.data.msg || '文章发布失败');
            }
          })
          .catch(error => {
            console.error('文章发布错误', error);
            this.$message.error('文章发布失败');
          });
      }).catch(() => {
        // 取消操作
      });
    },
    
    // 下架文章
    handleUnpublish(row) {
      this.$confirm('确定要下架该文章吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.put(`/api/admin/article/${row.id}/unpublish`)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('文章下架成功');
              this.fetchArticleList();
            } else {
              this.$message.error(response.data.msg || '文章下架失败');
            }
          })
          .catch(error => {
            console.error('文章下架错误', error);
            this.$message.error('文章下架失败');
          });
      }).catch(() => {
        // 取消操作
      });
    },
    
    // 删除文章
    handleDelete(row) {
      this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`/api/admin/article/${row.id}`)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('文章删除成功');
              this.fetchArticleList();
            } else {
              this.$message.error(response.data.msg || '文章删除失败');
            }
          })
          .catch(error => {
            console.error('文章删除错误', error);
            this.$message.error('文章删除失败');
          });
      }).catch(() => {
        // 取消删除操作
      });
    },
    
    // 分页大小变化
    handleSizeChange(val) {
      this.pagination.size = val;
      this.fetchArticleList();
    },
    
    // 当前页变化
    handleCurrentChange(val) {
      this.pagination.current = val;
      this.fetchArticleList();
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '草稿',
        1: '已发布',
        2: '已下架'
      };
      return statusMap[status] || '未知';
    },
    
    // 获取状态标签类型
    getStatusTagType(status) {
      const typeMap = {
        0: 'info',
        1: 'success',
        2: 'warning'
      };
      return typeMap[status] || '';
    },

    // 格式化日期参数
    formatDateParam(date) {
      if (!date) return null;
      const d = new Date(date);
      return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`;
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '-';
      try {
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) return '-'; // 处理无效日期
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
      } catch (error) {
        console.error('日期格式化错误:', error, dateStr);
        return '-';
      }
    },

    // 获取统计数据
    fetchStats() {
      this.statsLoading = true;
      axios.get('/api/admin/article/stats')
        .then(response => {
          if (response.data.code === 200) {
            this.stats = response.data.data || { total: 0, totalViewCount: 0, todayViewCount: 0 };
          } else {
            this.$message.error(response.data.msg || '获取统计数据失败');
          }
        })
        .catch(error => {
          console.error('获取统计数据错误', error);
          this.$message.error('获取统计数据失败');
        })
        .finally(() => {
          this.statsLoading = false;
        });
    }
  }
};
</script>

<style scoped>
.article-management {
  padding: 20px;
  min-height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.page-info {
  display: flex;
  align-items: center;
}

.stat-item {
  margin-left: 15px;
  font-size: 13px;
  color: #606266;
}

.box-card {
  flex: 1;
  margin-bottom: 20px;
  box-shadow: 0 4px 18px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

h2 {
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 18px;
}

.toolbar {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.toolbar > .el-button {
  margin-right: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.search-form .el-form-item {
  margin-bottom: 10px;
  margin-right: 10px;
}

.search-form .el-button {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.article-detail {
  max-width: 100%;
  overflow: hidden;
}

.article-title {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 20px;
  text-align: center;
}

.article-meta {
  color: #666;
  font-size: 14px;
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
}

.article-cover {
  text-align: center;
  margin-bottom: 20px;
}

.article-content {
  line-height: 1.8;
  margin-bottom: 20px;
}

.article-images h3 {
  margin-bottom: 10px;
  font-size: 16px;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
}

.empty-container {
  margin: 40px 0;
  text-align: center;
}

.data-summary {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: space-around;
}

.summary-item {
  text-align: center;
}

.summary-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.summary-value {
  font-size: 20px;
  color: #303133;
  font-weight: bold;
  margin: 0;
}

/* 表格行样式 */
::v-deep(.published-row) {
  background-color: #f0f9eb;
}

::v-deep(.unpublished-row) {
  background-color: #fdf6ec;
}

.title-cell {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.view-count {
  font-size: 12px;
  color: #909399;
}

.page-footer {
  margin-top: auto;
  padding: 15px 0;
  text-align: center;
  color: #909399;
}

.footer-content {
  padding: 15px 0;
  border-top: 1px solid #ebeef5;
}

.footer-links {
  margin-bottom: 10px;
}

.footer-links a {
  color: #606266;
  text-decoration: none;
}

.footer-links a:hover {
  color: #409EFF;
  text-decoration: underline;
}

.divider {
  margin: 0 10px;
}

.copyright {
  font-size: 12px;
}

.dialog-bottom-tips {
  margin-top: 15px;
  padding-top: 10px;
  border-top: 1px dashed #ebeef5;
  font-size: 12px;
  color: #909399;
}
</style> 